package com.weareint.common.utils;

import org.apache.commons.lang3.math.NumberUtils;

import javax.servlet.http.HttpServletRequest;

public abstract class IpUtil {

    /**
     * <pre>
     *      局域网（也可称为“私网”或“Lan侧”）通常情况都使用私有IP地址：
     *      A类：10.0.0.0-10.255.255.255
     *      B类：172.16.0.0-172.31.255.255
     *      C类：192.168.0.0-192.168.255.255
     * </pre>
     * @param ip ip
     * @return local ip true, otherwise false
     */
    public static boolean isLocalIp(String ip){
        if (null == ip){
            return false;
        }
        if (ip.startsWith("10.") || ip.startsWith("192.168.")){
            return true;
        }
        if (ip.startsWith("172.")){
            String tmp = ip.split("\\.")[1];
            int num = NumberUtils.toInt(tmp, -1);
            return num >= 16 && num <= 31;
        }
        return false;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if( null != ip && ip.contains(",")){
            ip = ip.split(",")[0];
        }
        return ip;

    }

}
